//
//  Top10Title.m
//  LilyBBS
//
//  Created by 李行 on 11-11-5.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "Top10Title.h"
#import "xpath.h"
#import "MessageCell.h"
#import "Top10Detail.h"
#import "LogIn.h"
#import "SingleCookie.h"
#import "Detail.h"
#import "Reachability.h"

@implementation Top10Title

@synthesize detail;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView
 {
 }
 */


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    self.tableView.rowHeight = 70;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque; 
    self.title = @"十大";
    [self getDetail];
    self.items = [self.detail objectAtIndex:0];
    
    if (_refreshHeaderView == nil) {
        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
        view.delegate = self;
        [self.tableView addSubview:view];
        _refreshHeaderView = view;
        [view release];
        
    }
    //  update the last update date
    [_refreshHeaderView refreshLastUpdatedDate];
    
    [super viewDidLoad];
}

-(void)viewWillAppear:(BOOL)animated{
    //若不存在cookie，则放置"登录"按钮
    if ([[SingleCookie sharedSingleCookie].savedCookies count]==0) {
        UIBarButtonItem *loginButton = [[UIBarButtonItem alloc] 
                                        initWithTitle:@"登录"                                            
                                        style:UIBarButtonItemStyleBordered 
                                        target:self 
                                        action:@selector(logIn)];
        self.navigationItem.rightBarButtonItem = loginButton; 
    }
    //若存在cookie，则将登录按钮去掉
    if ([[SingleCookie sharedSingleCookie].savedCookies count]!=0) {
        UIBarButtonItem *logoutButton = [[UIBarButtonItem alloc] 
                                         initWithTitle:@"退出"                                            
                                         style:UIBarButtonItemStyleBordered 
                                         target:self 
                                         action:@selector(logOut)];
        self.navigationItem.rightBarButtonItem =logoutButton;
    }
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            //没有网络连接
            NSLog(@" ");
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络好像连接不上。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        case ReachableViaWWAN:
            //使用3G网络            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络            
            break;
    }
    
    [self.tableView reloadData];
}


- (void)viewDidUnload
{
    _refreshHeaderView=nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//重写
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            //没有网络连接
            NSLog(@" ");
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络好像连接不上。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        case ReachableViaWWAN:
            //使用3G网络            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络            
            break;
    }
    
    Detail* webView = [[Detail alloc] initWithNibName:@"Detail" bundle:nil];
    NSString* href = [[@"http://bbs.nju.edu.cn/" stringByAppendingString:[[self.detail objectAtIndex:4]objectAtIndex:indexPath.row]] stringByAppendingFormat:@"&start=-1"];
    //NSURL* url = [[NSURL alloc] initWithString:href];
    //NSData* data = [[NSData alloc] initWithContentsOfURL:url];
    //[webView getDetail:data];
    webView.titlestring = [[self.detail objectAtIndex:0] objectAtIndex:indexPath.row];
    webView.urlString = [NSString stringWithString:href];
    [self.navigationController pushViewController:webView animated:YES];
    //[webView release];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    NSMutableArray* authors = [detail objectAtIndex:2];
    NSMutableArray* boards  = [detail objectAtIndex:1];
    
    UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    [cell.textLabel setNumberOfLines:2];
    //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    cell.textLabel.text = [items objectAtIndex:indexPath.row];
    NSString* author = @"作者：";
    NSString* board = @"   讨论区：";
    cell.detailTextLabel.text = [[[author stringByAppendingString:[[authors objectAtIndex:indexPath.row] description]] stringByAppendingString:board] stringByAppendingString:[[boards objectAtIndex:indexPath.row] description]];
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

-(void)getDetail{
    NSData *siteData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:TOP10]];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);    
    NSString *retStr = [[NSString alloc] initWithData:siteData encoding:enc];
    NSData* siteData2 = [retStr dataUsingEncoding:enc];
    [siteData release];
    [retStr release];
    
	TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:siteData2];
	NSMutableArray* titles = [xpathParser searchWithXPathQuery:TOP10_TITLE];
    NSMutableArray* boards = [xpathParser searchWithXPathQuery:TOP10_BOARD];
    NSMutableArray* authors = [xpathParser searchWithXPathQuery:TOP10_AUTHOR];
    NSMutableArray* follownumber = [xpathParser searchWithXPathQuery:TOP10_FOLLOWNUMBER];
    NSMutableArray* href = [xpathParser searchWithXPathQuery:TOP10_HREF];
	
    NSMutableArray* arr = [[NSMutableArray alloc] init];
    
    NSMutableArray* titlearr = [[NSMutableArray alloc] init];
	for (TFHppleElement *element in titles) {
        //NSLog(@"%@",[element description]);
		NSString *strs = [element content];
        if (strs==NULL) {
            continue;
        }
		[titlearr addObject:strs];
    }
    [arr addObject:titlearr];
    
    NSMutableArray* boardarr = [[NSMutableArray alloc] init];
	for (TFHppleElement *element in boards) {
		NSString *strs = [element content];
		[boardarr addObject:strs];
    }
    [arr addObject:boardarr];
    
    NSMutableArray* authorarr = [[NSMutableArray alloc] init];
	for (TFHppleElement *element in authors) {
		NSString *strs = [element content];
		[authorarr addObject:strs];
    }
    [arr addObject:authorarr];
    
    NSMutableArray* follownumberarr = [[NSMutableArray alloc] init];
	for (TFHppleElement *element in follownumber) {
		NSString *strs = [element content];
		[follownumberarr addObject:strs];
    }
    [arr addObject:follownumber];
    
    NSMutableArray* hrefarr = [[NSMutableArray alloc] init];
	for (TFHppleElement *element in href) {
		NSString *strs = [element content];
        //NSLog(@"%@",strs);
		[hrefarr addObject:strs];
    }
    [arr addObject:hrefarr];
    
	self.detail = arr;
	[arr release];
    [titlearr release];
    [boardarr release];
    [authorarr release];
    [follownumberarr release];
	[xpathParser release];
}

-(void)logIn{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            //没有网络连接
            NSLog(@" ");
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络好像连接不上。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        case ReachableViaWWAN:
            //使用3G网络            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络            
            break;
    }
    
    //NSLog(@"logging in...");
    LogIn* login = [[LogIn alloc] initWithNibName:@"LogIn" bundle:nil];
    UINavigationController *addNavCon = [[UINavigationController alloc] initWithRootViewController:login];
    [self presentModalViewController:addNavCon animated:YES];
    [login release];
}

-(void)logOut{
    //NSLog(@"logging out...");
    [SingleCookie sharedSingleCookie].savedCookies = nil;
    /*UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"退出提示" message:@"退出成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
     [alert show];*/
    UIBarButtonItem *loginButton = [[UIBarButtonItem alloc] 
                                    initWithTitle:@"登录"                                            
                                    style:UIBarButtonItemStyleBordered 
                                    target:self 
                                    action:@selector(logIn)];
    self.navigationItem.rightBarButtonItem = loginButton;
    [loginButton release];
}

-(void)dealloc{
    _refreshHeaderView = nil;
    [super dealloc];
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
    //  should be calling your tableviews data source model to reload
    //  put here just for demo
    _reloading = YES;
    [self getDetail];
}

- (void)doneLoadingTableViewData{
    //  model should call this when its done loading
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.0];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    return _reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    return [NSDate date]; // should return date data source was last changed
}

@end
